# -*- coding: utf-8 -*-
"""
Created on Mon Oct 07 15:24:46 2013

@author: jkwong
"""

#PBAR_MatchMarkerFile.py

# need this to read in cargo files
import PBAR_Cargo
import os
import codecs
import shutil
import copy
import numpy as np
import sys

def PBAR_ModifyCargoMarker(filename, offset):
    # Check to see if the file exists
    if not os.path.exists(filename):
        print("File does not exists. Quitting")
        return
    filenameOld = filename.replace('.cargomarker', '.cargomarkerBeforeShift')
    # see if the file has already been shifted
    if os.path.exists(filenameOld):
        print("The file has already been converted. Quitting")
        return
    else: # make back up of file
        try:
            shutil.copy(filename, filenameOld)
        except:
            print("Could not copy file")
            return
            
    # open old file for reading
    with codecs.open(filenameOld, 'rb', encoding = 'utf-16') as fidOld:
        # open file for writting
        with codecs.open(filename, 'wb', encoding = 'utf-16') as fid:
            # Check to see if the file has been convereted already by checking for existence of cargomarkerOLD file.
            for lineIn in fidOld:
                if len(lineIn) < 3:
                    fid.write(lineIn) # the first line seems to contain some whitespace
                else:
                    lineIn2 = copy.copy(lineIn)
                    # Modify the entires
                    preStringList = ['left=', 'right=', 'center x=', 'left x=', 'right x=']                    
                    # cycle through the list of x direction values.
                    for (index, preString) in enumerate(preStringList):
                        # check if it actually exists
                        if lineIn2.find(preString) > -1:
                            index1 = lineIn2.find(preString) + len(preString) + 1 # index of largest digit
                            index2 = lineIn2[index1:].find('"')+index1 # index parenthesis to the right of the smallest digit
                            theNumber = int(lineIn2[index1:index2]) + offset
                            lineIn2 = u'%s%d%s' %(lineIn2[:index1], theNumber, lineIn2[index2:])
                    #write the modified line to the new file
                    fid.write(lineIn2)
    fid.close()
    fidOld.close()
    print('Created: %s' %filename)
    
if __name__ == "__main__":
    startBin1 = PBAR_Cargo.FindCargoStart(sys.argv[1])
    startBin2 = PBAR_Cargo.FindCargoStart(sys.argv[2])
    offset = startBin2 - startBin1
    print("Offset: %d" %offset)
    filename = sys.argv[2]
    filename = filename.replace('DR', 'cargomarker')
    PBAR_ModifyCargoMarker(filename, offset)

